//
//  PersonCenterViewController.m
//  GoldOperationClient
//
//  Created by yaxue wang on 16/8/4.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "PersonCenterViewController.h"
#import "PersonPassViewController.h"
#import "PersonPhoneViewController.h"
#import "ImageUtil.h"
#import "CBaseTable.h"
#import "LoginViewController.h"
#import "AppDelegate.h"
#import "CQiniuFileUpload.h"
#import "QNUploadOption.h"
#import "CFileUpload.h"
#import "UIImage+ResizeMagick.h"
#import "SDImageCache.h"
#import "UIImageView+WebCache.h"
#import "UpdateVersionView.h"
#import "PersonCodeViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface PersonCenterViewController()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITableViewDelegate,UITableViewDataSource>
{
    UIImageView *headImg;
    UITableView *table;
    CGFloat offtY;
    CBaseTable *_table;
    NSDictionary *_dataDic;
    NSArray *_ar;
    NSString *phone;
    NSString *address;
    BOOL isNewImg;
    NSMutableArray *_photosAr;
    UIImage *_newIamge;
    NSString *_netWorkversion;

}

@end
@implementation PersonCenterViewController
- (void)viewWillAppear:(BOOL)animated
{
  
    [super viewWillAppear:animated];
    [self.view bringSubviewToFront: self.mainTabBar ];

    [CClass HttpRequestTask:YES withUrl:@"reviseaccount_selectCustomer" withData:@{@"uuid":[CClass getCacheData:NSUD_UUID]} notifyError:YES onSuccess:^(BaseModel *model) {
        [CClass saveCacheData:[model.B_data objectForKey:@"name"] key:NSUD_Name];
        [CClass saveCacheData:[model.B_data objectForKey:@"province"] key:NSUD_Province];
        [CClass saveCacheData:[model.B_data objectForKey:@"city"] key:NSUD_City];
        [CClass saveCacheData:[model.B_data objectForKey:@"mobile"] key:NSUD_Mobile];
        [CClass saveCacheData:[model.B_data objectForKey:@"serviceName"] key:NSUD_ServiceName];
        _ar =[[NSArray alloc]initWithObjects:@"所在服务商",@"所在地",@"密码",nil];//@"版本号",
        _dataDic=model.B_data;
        [_table reloadData];
        
    } onError:^(BaseModel *model) {

    }];


}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return  UIStatusBarStyleLightContent;
}
- (void)initView
{
//    [super initView];
    self.navBar.hidden=NO;

    [self setTitle:@"我的"];
    _photosAr=[[NSMutableArray alloc]init];

    _dataDic =[[NSDictionary alloc]init];
    _table =[[CBaseTable alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, WindowHeight)style:UITableViewStyleGrouped];
    _table.separatorStyle =UITableViewCellSelectionStyleNone;
    _table.delegate =self;
    _table.dataSource=self;
    _table.scrollEnabled=NO;
    _table.backgroundColor=BackColor;
    [self.view addSubview:_table];
    UIView *foot =[self footView];
    _table.tableFooterView =foot;

}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    UIImage *centBG=[UIImage imageNamed:@"Ico_center_bg"];
    return centBG.size.height;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIImage *centBG=[UIImage imageNamed:@"Ico_center_bg"];
    UIView *bgView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, centBG.size.height)];
    UIImageView *topView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, centBG.size.height)];
    topView.image=centBG;
    topView.userInteractionEnabled=YES;
    [bgView addSubview:topView];
    
    UIView *narView =[[UIView alloc]initWithFrame:CGRectMake(0, 0, WindowWidth, 64)];
    narView.backgroundColor =[UIColor clearColor];
    [topView addSubview:narView];
  
    
    UILabel *titleLab =[[UILabel alloc]init];
    [narView addSubview:titleLab];
    [titleLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(narView);
        make.top.equalTo(narView).offset(30);
    }];
    titleLab.text=@"我的";
    titleLab.font =F(16);
    titleLab.textColor =[UIColor whiteColor];
//    UIView *scanBg=[[UIView alloc]initWithFrame:CGRectMake(WindowWidth-100, 20, 100, 50)];
//    scanBg.backgroundColor=[UIColor clearColor];
//    [topView addSubview:scanBg];
//    UIImage *image =[UIImage imageNamed:@"Ico_center_scan"];
//    UIImageView *scanImg=[[UIImageView alloc]initWithFrame:CGRectMake(scanBg.bounds.size.width-image.size.width-25, (scanBg.bounds.size.height-image.size.height)/2, image.size.width, image.size.height)];
//    scanImg.image=image;
//    scanImg.userInteractionEnabled=YES;
//    [scanBg addSubview:scanImg];
//    [scanBg bk_whenTapped:^{
//        
//        PersonCodeViewController *personVC=[[PersonCodeViewController alloc]init];
//    
//        [self pushController:personVC];
//
//       
//    }];
    
    
    UIImageView *headBG=[[UIImageView alloc]initWithFrame:CGRectMake(30, topView.bounds.size.height-30-85, 85, 85)];
    headBG.image=[UIImage imageNamed:@"Ico_center_headBg"];
    headBG.userInteractionEnabled=YES;
    [topView addSubview:headBG];
    
    headImg=[[UIImageView alloc]initWithFrame:CGRectMake(3,3, 85-6, 85-6)];
    headImg.layer.masksToBounds =YES;
    headImg.layer.cornerRadius =79/2;
    //从本地找到
    headImg.image= [CClass GetImageFromLocal:NSUD_HeadImg];
    

    [headBG addSubview:headImg];
    
    headImg.userInteractionEnabled=YES;
    [headImg bk_whenTapped:^{
        //头像
       [self chooseClick];
    

    }];
    UILabel *nameLab =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headBG.frame)+20,topView.bounds.size.height-60, 150, 20)];
    nameLab.font =F(16);


    if ([[CClass getCacheData:NSUD_Name] isEqualToString:@""]){
        if ([F_NSpace([_dataDic objectForKey:@"name"]) isEqualToString:@""])
        {
            nameLab.text=[_dataDic objectForKey:@""];
        }else
        {
            nameLab.text=[_dataDic objectForKey:@"name"];
        }
    }else
    {
        nameLab.text=[CClass getCacheData:NSUD_Name];
        
    }
    nameLab.textColor =[UIColor whiteColor];
    [topView addSubview:nameLab];
    UILabel *phoneLab =[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(headBG.frame)+20,topView.bounds.size.height-30, 180, 16)];
    phoneLab.font =F(12);
    phoneLab.text=[_dataDic objectForKey:@"mobile"];

    if ([[CClass getCacheData:NSUD_Mobile] isEqualToString:@""]){
        if ([F_NSpace([_dataDic objectForKey:@"mobile"]) isEqualToString:@""])
        {
            phoneLab.text=[_dataDic objectForKey:@""];
        }else
        {
            phoneLab.text=[_dataDic objectForKey:@"mobile"];
        }
    }else
    {
        phoneLab.text=[CClass getCacheData:NSUD_Mobile];
        
    }
    phoneLab.textColor =[UIColor whiteColor];
    [topView addSubview:phoneLab];
    UIImage *editImg=[UIImage imageNamed:@"Ico_center_edit"];
    UIView *editView=[[UIView alloc]initWithFrame:CGRectMake(WindowWidth-60-editImg.size.width, topView.bounds.size.height-30, 60+editImg.size.width, editImg.size.height)];
    [topView addSubview:editView];
    UIImageView *editImageView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, editImg.size.width, editImg.size.height)];
    editImageView.image=editImg;
    editImageView.userInteractionEnabled=YES;
    [editView addSubview:editImageView];
    UILabel *editLab =[[UILabel alloc]initWithFrame:CGRectMake(editImg.size.width+10,0, 50, editImg.size.height)];
    editLab.font =F(14);
    editLab.text =@"修改";
    editLab.userInteractionEnabled=YES;
    editLab.textColor =[UIColor whiteColor];
    [editView addSubview:editLab];
    [editView bk_whenTapped:^{
        
        if ([F_NSpace([_dataDic objectForKey:@"mobile"]) isEqualToString:@""])
        {
            
        }else
        {
            PersonPhoneViewController *personPhoneVC= [[PersonPhoneViewController alloc]init];
            personPhoneVC.phone =[_dataDic objectForKey:@"mobile"];
            [self pushController:personPhoneVC];
            
        }
    }];
    
    return bgView;
    
}

- (UIView*)footView{
    UIView *footView =[[UIView alloc]init];
    footView.frame=CGRectMake(0, 0, WindowWidth, 82);
    UIButton *button =[UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(28,40, WindowWidth-56, 42);
    if (WindowHeight==480) {
        footView.frame=CGRectMake(0, 0, WindowWidth, 30);
        button.frame = CGRectMake(28,0, WindowWidth-56, 30);
        
    }
    [footView addSubview:button];
    [button setBackgroundColor:C(@"f66544")];
    button.layer.masksToBounds=YES;
    button.layer.cornerRadius=4;
    [button setTitle:@"退出登录" forState:UIControlStateNormal];
    button.titleLabel.font =F(16);
    [button bk_addEventHandler:^(id sender) {
        //退出请求
        [self setIsLoading:YES];
        [CClass HttpRequestTask:YES withUrl:@"loginout_authtoken" withData:nil notifyError:YES onSuccess:^(BaseModel *model) {
            //把定位关闭
            [(AppDelegate *)[[UIApplication sharedApplication] delegate] canleTimer];
            [(AppDelegate *)[[UIApplication sharedApplication] delegate] unRegisterPush];
            
            [self setIsLoading:NO];
            [CClass clearCacheData:@[NSUD_Token, NSUD_UUID,NSUD_state,NSUD_HeadImg,NSUD_City,NSUD_Province,NSUD_Mobile,NSUD_Name,NSUD_ServiceName,NSUD_state,NSUD_HistoryCache,NSUD_HomeCache,NSUD_Uuid]];
            [[[SDWebImageManager sharedManager] imageCache] clearDisk];
            [[[SDWebImageManager sharedManager] imageCache] clearMemory];
            if([UIDevice currentDevice].systemVersion.floatValue == 7.0f)
            {
                [[NSURLCache sharedURLCache] removeAllCachedResponses];
                
            }

            [CClass showMessage:@"退出成功" completion:^{
                self.mainTabBar.showIndex = 0;
                [self login];
            }];
            
        } onError:^(BaseModel *model) {
            
        }];
 
       
        
        
        
    } forControlEvents:UIControlEventTouchUpInside];
    return footView;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _ar.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 48;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        UIImage *image1 = [UIImage imageNamed:@"Ico_center1"];
        UIImageView *headImgView = [[UIImageView alloc] initWithFrame:CGRectMake(23, (48-image1.size.height)/2, image1.size.width, image1.size.height)];
        
        headImgView.tag=500;
        [cell addSubview:headImgView];
        UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(23+image1.size.width+12, 0, 80, 48)];
        titleLabel.backgroundColor = [UIColor clearColor];
        titleLabel.font = F(14);
        titleLabel.tag=100;
        titleLabel.textColor = FontColor;
        [cell addSubview:titleLabel];
        
        UILabel *rightLab = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, WindowWidth -113, 48)];
        rightLab.backgroundColor = [UIColor clearColor];
        rightLab.font = F(12);
        rightLab.tag=200;
        rightLab.textAlignment =NSTextAlignmentRight;
        rightLab.textColor = LightFontColor;
        [cell addSubview:rightLab];
        UIImage *image = [UIImage imageNamed:@"Ico_goNext"];
        UIImageView *nextImgeView = [[UIImageView alloc] initWithFrame:CGRectMake(WindowWidth-15-image.size.width, (48-image.size.height)/2, image.size.width, image.size.height)];
        
        nextImgeView.tag=400;
        [cell addSubview:nextImgeView];
        
        UILabel *line1 =[[UILabel alloc]initWithFrame:CGRectMake(20,48-0.5, WindowWidth-20, 0.5)];
        line1.tag =300;
        [cell addSubview:line1];
   }
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];

    cell.backgroundColor =[UIColor whiteColor];

    UILabel *title =[cell viewWithTag:100];
    title.text =[_ar objectAtIndex:indexPath.row];
    UILabel *detail =[cell viewWithTag:200];
    UILabel *line =[cell viewWithTag:300];
    line.backgroundColor =LineColor;
    UIImageView *img =[cell viewWithTag:400];
    UIImage *image=[UIImage imageNamed:@"Ico_goNext"];
    img.image =image;

    UIImageView *headImgView =[cell viewWithTag:500];
    headImgView.image =[UIImage imageNamed:[NSString stringWithFormat:@"Ico_center%d",indexPath.row+1]];
    if (indexPath.row==0) {
        title.frame=CGRectMake(CGRectGetMaxX(headImgView.frame)+12, 0, 90, 48);
        detail.frame=CGRectMake(CGRectGetMaxX(title.frame)+6, 0, WindowWidth-CGRectGetMaxX(title.frame)-15-image.size.width, 48);
        detail.numberOfLines=0;
        if ([[CClass getCacheData:NSUD_ServiceName] isEqualToString:@""]){
            if ([F_NSpace([_dataDic objectForKey:@"serviceName"]) isEqualToString:@""])
            {
                detail.text=[_dataDic objectForKey:@""];
            }else
            {
                detail.text=[_dataDic objectForKey:@"serviceName"];
            }
        }else
        {
            detail.text=[CClass getCacheData:NSUD_ServiceName];
            
        }
    
        img.image =[UIImage imageNamed:@""];


    }else if(indexPath.row==1)
        
    {
        title.frame=CGRectMake(CGRectGetMaxX(headImgView.frame)+12, 0, 90, 48);
        detail.frame=CGRectMake(CGRectGetMaxX(title.frame)+6, 0, WindowWidth-CGRectGetMaxX(title.frame)-15-image.size.width, 48);
        detail.numberOfLines=0;
        NSString *city;
        NSString*province;
        if ([[CClass getCacheData:NSUD_Province] isEqualToString:@""]||[[CClass getCacheData:NSUD_City] isEqualToString:@""]){
            if ([F_NSpace([_dataDic objectForKey:@"province"]) isEqualToString:@""])
            {
                province=@"";
            }else
            {
               province=[NSString stringWithFormat:@"%@",[_dataDic objectForKey:@"province"]];
            }
            if ([[CClass getCacheData:NSUD_City] isEqualToString:@""]){
                if ([F_NSpace([_dataDic objectForKey:@"city"]) isEqualToString:@""])
                {
                    city=@"";
                }else
                {
                    city=[_dataDic objectForKey:@"city"];
                }
            }
             detail.text=[NSString stringWithFormat:@"%@.%@",province,city];

        }else
        {
            detail.text=[NSString stringWithFormat:@"%@.%@",[CClass getCacheData:NSUD_Province],[CClass getCacheData:NSUD_City]];

            
        }
        
       
        
        img.image =[UIImage imageNamed:@""];

 
    }else if(indexPath.row==2)
            
        {
            detail.text=@"修改";

            
            
        }else if(indexPath.row==3)
        {
            NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
         NSString* versionNum =[infoDict objectForKey:@"CFBundleShortVersionString"];
            detail.text=versionNum;
         


        }

    return cell;
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
   
       
    if (indexPath.row==2) {
       
    {
        PersonPassViewController *personVC= [[PersonPassViewController alloc]init];
        [self pushController:personVC];
    }
    }else  if (indexPath.row==3)
    {
//        NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
//        NSString* versionNum =[infoDict objectForKey:@"CFBundleShortVersionString"];
//        [CClass HttpRequestTask:YES withUrl:@"appversion_showProVersion" withData:nil notifyError:YES onSuccess:^(BaseModel *model) {
//            if ([F_NSpace([model.B_data objectForKey:@"latest_version"]) isEqualToString:@""])
//            {
//                _netWorkversion=@"0";
//            }else
//            {
//                _netWorkversion=[model.B_data objectForKey:@"latest_version"];//本地大于等于网络的不更新//@"2.2.2";//
//                
//            }
//            //是最新
//            if (([_netWorkversion compare:versionNum options:NSNumericSearch]==NSOrderedAscending)||([_netWorkversion compare:versionNum options:NSNumericSearch]==NSOrderedSame))  {
//                
//                //是最新
//                NSString *text =[NSString stringWithFormat:@"当前版本V%@\n已是最新版本。",versionNum];
//                [UpdateVersionView showImg:[UIImage imageNamed:@"Ico_center_update"]Title:@"检测版本提示" BtnTitle:@"确定" context:text action:^(NSInteger index) {
//                    
//                }];
//
//                
//                
//            }
//            else
//            {
//                //不是最新的
//                NSString *text =[NSString stringWithFormat:@"当前版本V%@\n有新版本。",versionNum];
//                [UpdateVersionView showImg:[UIImage imageNamed:@"Ico_center_update"]Title:@"检测版本提示" BtnTitle:@"确定" context:text action:^(NSInteger index) {
//
//                    
//                }];
//                
//                
//            }
//            
//            
//        } onError:^(BaseModel *model) {
//            
//        }];
        
     
           
    }
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (void) login{
    [self.navigationController popToRootViewControllerAnimated:NO];
    AppDelegate *delegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    [delegate login];

}

//打开系统相册
#pragma mark -- 打开系统相册
-(void)chooseClick{
    UIActionSheet *sheet;
    
    //判断是否支持相机
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"拍照", @"从相册中选取", nil];
    }else{
        sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self
                                   cancelButtonTitle:@"取消"
                              destructiveButtonTitle:nil
                                   otherButtonTitles:@"从相册中选取", nil];
    }
    sheet.actionSheetStyle=UIActionSheetStyleBlackOpaque;
    sheet.tag = 200;
    [sheet showInView:self.view];
}

#pragma mark -- 判断是否支持相机 ，跳转到相机 或相册界面
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 200){
        NSInteger sourceType = 0;
        //判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
            switch (buttonIndex){
                case 0:
                    //相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    //取消
                    return;
                    break;
                default:
                    break;
            }
        }else{
            if (buttonIndex == 0){
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }else if(buttonIndex==1){
                return;
            }
        }
        
        //跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc]init];
        imagePickerController.delegate = self;
        imagePickerController.sourceType = sourceType;
        imagePickerController.allowsEditing = NO;
        //状态栏变成白色
        [self presentViewController:imagePickerController animated:YES completion:nil];
    }
}

- (void)navigationController:(UINavigationController *)navigationController willShowViewController:(UIViewController *)viewController animated:(BOOL)animated {
   [navigationController.navigationBar setBackgroundColor:[UIColor whiteColor]];
    [navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];
    navigationController.navigationBar.translucent = NO;
    [[UIApplication  sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
    [[UIApplication  sharedApplication]  setStatusBarHidden:NO];
}

#pragma mark -- UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    
    dispatch_async(dispatch_get_main_queue(), ^{
//        picker.allowsEditing=YES;
        // _headImg.image = image;
        //设置image的尺寸
        //初始化imageNew为从相机中获得的-- 压缩
        UIImage *imageNew = [info objectForKey:UIImagePickerControllerOriginalImage];
        NSData *imageData=  [CClass compressImageQuality:imageNew];
        _newIamge=[UIImage imageWithData:imageData];
        [_photosAr removeAllObjects];
        [_photosAr addObject:imageNew];
        isNewImg=YES;
        [self dismissViewControllerAnimated:YES completion:nil];
        //上传头像
        if(_photosAr.count>0)
        {
            //图片 上传图片
            NSString *imgName = [NSString stringWithFormat:@"%@_%@.jpg", [Common getDateTimeString], [Common randomStringWithLength:8]];
            NSData *data =[_newIamge resizedAndReturnData];
            NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
            
            [dic setObject:imgName forKey:@"headImg"];
            
            [self setIsLoading:YES];
            
            [[CQiniuFileUpload uploadFile]uploadFiles:[CFileModel initWithFile:data name:imgName] progress:^(CFileUpload *upload, float per) {
                
            } finish:^(CFileUpload *upload, NSArray *models, NSError *error) {
                //成功之后发送
                
                [CClass HttpRequestTask:YES withUrl:@"reviseaccount_saveHeadImg" withData:dic notifyError:YES onSuccess:^(BaseModel *model) {
                    headImg.image=imageNew;
                    [CClass SaveImageToLocal:imageNew Keys:NSUD_HeadImg];

                    
                    [CClass showLittleTimeMessage:@"更换成功" completion:^{
                        [self setIsLoading:NO];
                        
                        
                    }];
                } onError:^(BaseModel *model) {
                    self.isLoading=NO;

                }];
                
            }];
        }

       
    });
}


-(void) imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    [picker dismissViewControllerAnimated:YES completion:^{}];
}




@end
